import React from 'react'
import { View, Text } from 'react-native'
import { Card, Badge, Icon } from '@rneui/themed'
import { ApprovalNodeInfo, TaskStatus } from '../api/process'
import { formatDate } from '../utils/dateFormatter'

interface ProcessTimelineProps {
    /** 审批节点信息数组 */
    activityNodes: ApprovalNodeInfo[]
    /** 自定义样式 */
    style?: any
    /** 标题文本 */
    title?: string
    /** 空数据时的提示文本 */
    emptyText?: string
}

/**
 * 通用流程时间线组件
 */
const ProcessTimeline: React.FC<ProcessTimelineProps> = ({
    activityNodes,
    title = '流程信息',
    emptyText = '暂无流程信息'
}) => {
    // 获取节点状态图标
    const getNodeStatusIcon = (status: number) => {
        switch (status) {
            case TaskStatus.COMPLETED:
                return 'check-circle'
            case TaskStatus.IN_PROGRESS:
                return 'clock'
            case TaskStatus.REJECTED:
                return 'x-circle'
            case TaskStatus.CANCELLED:
                return 'slash'
            default:
                return 'circle'
        }
    }

    // 获取节点状态颜色
    const getNodeStatusColor = (status: number) => {
        switch (status) {
            case TaskStatus.COMPLETED:
                return '#10b981'
            case TaskStatus.IN_PROGRESS:
                return '#f59e0b'
            case TaskStatus.REJECTED:
                return '#ef4444'
            case TaskStatus.CANCELLED:
                return '#6b7280'
            default:
                return '#d1d5db'
        }
    }

    // 获取节点状态文本
    const getNodeStatusText = (status: number) => {
        switch (status) {
            case TaskStatus.COMPLETED:
                return '已完成'
            case TaskStatus.IN_PROGRESS:
                return '进行中'
            case TaskStatus.REJECTED:
                return '已拒绝'
            case TaskStatus.CANCELLED:
                return '已取消'
            default:
                return '未开始'
        }
    }

    // 如果没有数据，显示空状态
    if (!activityNodes || activityNodes.length === 0) {
        return (
            <Card containerStyle={styles.cardContainer}>
                <Text style={styles.cardTitle}>
                    {title}
                </Text>
                <Text style={styles.emptyText}>
                    {emptyText}
                </Text>
            </Card>
        )
    }

    return (
        <Card containerStyle={styles.cardContainer}>
            <Text style={styles.cardTitle}>
                {title}
            </Text>
            
            <View style={styles.timelineContainer}>
                {activityNodes.map((node, index) => (
                    <View key={`node-${node.id || index}-${index}`} style={styles.nodeContainer}>
                        {/* 节点状态图标 */}
                        <View style={[styles.nodeIcon, { backgroundColor: getNodeStatusColor(node.status) }]}>
                            <Icon 
                                name={getNodeStatusIcon(node.status)} 
                                type="feather" 
                                size={10} 
                                color="#fff" 
                            />
                        </View>
                        
                        {/* 节点内容 */}
                        <View style={styles.nodeContent}>
                            {/* 节点头部：名称和状态 */}
                            <View style={styles.nodeHeader}>
                                <Text style={styles.nodeName}>
                                    {node.name}
                                </Text>
                                
                                <Badge
                                    value={getNodeStatusText(node.status)}
                                    badgeStyle={[styles.statusBadge, { backgroundColor: getNodeStatusColor(node.status) }]}
                                    textStyle={styles.statusBadgeText}
                                />
                            </View>
                            
                            {/* 节点时间信息 */}
                            {node.startTime && (
                                <Text style={styles.timeText}>
                                    开始时间: {formatDate(node.startTime)}
                                </Text>
                            )}
                            {node.endTime && (
                                <Text style={styles.timeText}>
                                    完成时间: {formatDate(node.endTime)}
                                </Text>
                            )}
                            
                            {/* 审批人信息 */}
                            <View style={styles.approverContainer}>
                                {/* 情况一：遍历每个审批节点下的【进行中】task 任务 */}
                                {node.tasks && node.tasks.length > 0 && (
                                    <View style={styles.taskContainer}>
                                        {node.tasks.map((task, taskIndex) => (
                                            <View key={`task-${node.id}-${task.id || taskIndex}`} style={styles.approverItem}>
                                                {/* 审批人信息 */}
                                                <View style={styles.approverHeader}>
                                                    {(task.assigneeUser?.nickname || task.ownerUser?.nickname) && (
                                                        <>
                                                            <Icon 
                                                                name="user" 
                                                                type="feather" 
                                                                size={14} 
                                                                color="#666" 
                                                                style={styles.userIcon}
                                                            />
                                                            <Text style={styles.approverName}>
                                                                {task.assigneeUser?.nickname || task.ownerUser?.nickname}
                                                            </Text>
                                                        </>
                                                    )}
                                                </View>
                                                
                                                {/* 审批意见 */}
                                                {task.reason && (
                                                    <Text style={styles.approvalReason}>
                                                        审批意见：{task.reason}
                                                    </Text>
                                                )}
                                                
                                                {/* 审批时间 */}
                                                {task.createTime && (
                                                    <Text style={styles.approvalTime}>
                                                        {formatDate(task.createTime)}
                                                    </Text>
                                                )}
                                            </View>
                                        ))}
                                    </View>
                                )}
                                
                                {/* 情况二：遍历每个审批节点下的【候选的】task 任务 */}
                                {node.candidateUsers && node.candidateUsers.length > 0 && (
                                    <View style={styles.candidateContainer}>
                                        {node.candidateUsers.map((user, userIndex) => (
                                            <View key={`candidate-${node.id}-${user.id || userIndex}`} style={styles.approverItem}>
                                                <View style={styles.approverHeader}>
                                                    <Icon 
                                                        name="user" 
                                                        type="feather" 
                                                        size={14} 
                                                        color="#666" 
                                                        style={styles.userIcon}
                                                    />
                                                    <Text style={styles.approverName}>
                                                        {user.nickname || `用户${userIndex + 1}`}
                                                    </Text>
                                                </View>
                                            </View>
                                        ))}
                                    </View>
                                )}
                            </View>
                        </View>
                        
                        {/* 连接线 - 使用 flex 布局自动填充剩余空间 */}
                        {index < activityNodes.length - 1 && (
                            <View style={styles.connectorLine} />
                        )}
                    </View>
                ))}
            </View>
        </Card>
    )
}

// 样式定义
const styles = {
    cardContainer: {
        borderRadius: 12,
        marginHorizontal: 16,
        marginVertical: 8,
        backgroundColor: '#fff',
        shadowColor: 'transparent',
        shadowOffset: {
            width: 0,
            height: 0,
        },
        shadowOpacity: 0,
        shadowRadius: 0,
        elevation: 0,
        borderWidth: 0,
    },
    cardTitle: {
        fontSize: 16,
        fontWeight: 'bold' as const,
        marginBottom: 12
    },
    emptyText: {
        color: '#666',
        textAlign: 'center' as const,
        paddingVertical: 20
    },
    timelineContainer: {
        paddingLeft: 16
    },
    nodeContainer: {
        position: 'relative' as const
    },
    nodeIcon: {
        position: 'absolute' as const,
        left: -8,
        top: 8,
        width: 16,
        height: 16,
        borderRadius: 8,
        justifyContent: 'center' as const,
        alignItems: 'center' as const,
        zIndex: 1
    },
    nodeContent: {
        marginLeft: 20,
        paddingBottom: 16
    },
    nodeHeader: {
        flexDirection: 'row' as const,
        justifyContent: 'space-between' as const,
        alignItems: 'center' as const,
        marginBottom: 8
    },
    nodeName: {
        fontSize: 14,
        fontWeight: '600' as const,
        color: '#333',
        flex: 1
    },
    statusBadge: {
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 16,
        minWidth: 60,
        height: 28
    },
    statusBadgeText: {
        fontSize: 12,
        color: '#fff',
        fontWeight: '500' as const
    },
    timeText: {
        fontSize: 12,
        color: '#666',
        marginBottom: 4
    },
    approverContainer: {
        marginTop: 8
    },
    taskContainer: {
        // marginBottom: 8
    },
    candidateContainer: {
        // marginTop: 8
    },
    approverItem: {
        backgroundColor: '#f8f9fa',
        padding: 12,
        borderRadius: 8,
        marginBottom: 8
    },
    approverHeader: {
        flexDirection: 'row' as const,
        alignItems: 'center' as const,
        marginBottom: 6
    },
    userIcon: {
        marginRight: 6
    },
    approverName: {
        fontSize: 13,
        color: '#333',
        fontWeight: '500' as const
    },
    approvalReason: {
        fontSize: 12,
        color: '#666',
        marginBottom: 4,
        fontStyle: 'italic' as const
    },
    approvalTime: {
        fontSize: 11,
        color: '#999'
    },
    connectorLine: {
        position: 'absolute' as const,
        left: 0,
        top: 24,
        width: 2,
        bottom: -16,
        backgroundColor: '#e5e7eb'
    }
}

export default ProcessTimeline
